package com.yifi.system.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.yifi.common.DBHelper;
import com.yifi.common.SysUtil;
import com.yifi.common.base.BaseController;
import com.yifi.common.model.AjaxResult;
import com.yifi.common.utils.DbUtils;
import com.yifi.common.utils.FileUtils;
import com.yifi.common.utils.StringUtils;
import com.yifi.common.utils.ToolSession;
import com.yifi.system.service.MisOrgService;
import com.yifi.system.service.MisUserService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;

@Path(value="/sysuser",viewPath = "/")
public class SysUserController extends BaseController {

	@Inject
	private MisUserService misUserService;
	
	public void index()
	{
		String c_pro = ToolSession.getUser(this).getC_pro();
		set("c_pro", c_pro);
		render("system/sysuser.html");
	}

	@Inject
	private MisOrgService misOrgService;
	public void getOrgTree()
	{
		String c_pro=getPara("c_pro","");
		List<Record> list=misOrgService.getTree("id","name",null,"",c_pro);
		
		renderJson(list);
	}
	
	
	public void list()
	{
		String c_pro=getPara("c_pro","");
		String cpost = getPara("cpost", "");
		String cname = getPara("cname", "");
		String bm = getPara("cdept", "");
		boolean isleaf = getParaToBoolean("isleaf", true);

		String sqlSelect = "select t1.*,(case when is_ld='1' then 1 else 0 end) as isld "
				+ ",(select cname from mis_org where ccode=t1.cdept) as cbm ";
		String sqlExcept=" from mis_user t1 where 1=1 ";
		if (!bm.equals("")) {
			if (isleaf)// 下级部门用户
			{
				sqlExcept += " and t1.cdept like '" + bm + "%'";
			} else {
				sqlExcept += " and t1.cdept = '" + bm + "'";
			}
		}
		if (!cname.equals("")) {
			sqlExcept += " and (t1.cname like '%" + cname + "%' or t1.user_num like '%" + cname + "%')";
		}
		
		if(!cpost.equals(""))
		{
			sqlExcept+=" and t1.ccode not in (select ccode from mis_user_post where cpost='"+cpost+"')";
		}
		if(StrUtil.isNotEmpty(c_pro))
		{
			sqlExcept+=" and t1.c_pro='"+c_pro+"' ";
		}
		
		sqlExcept += " order by cdept,st_flag desc,isort,ccode";
		
		renderJson(getDataTable(sqlSelect,sqlExcept));
	}
	
	public void getData()
	{
		String ccode=getPara("ccode","");
		String sql="select t1.*,(select cname from mis_org where ccode=t1.cdept) as cdeptname from mis_user t1 where t1.ccode=?";
		Record record=Db.findFirst(sql, ccode);
		if(record==null)
		{
			record=new Record();
		}
		
		renderJson(record);
	}
	//编辑新增
	public void edit()
	{
		String ccode=getPara("ccode","");
		set("ccode", ccode);
		
		String c_pro=getPara("c_pro","");
		set("c_pro", c_pro);
		
		render("system/sysuser_edit.html");
	}
	
	public void save()
	{
		String ccode=getPara("ccode","");
		String user_num = getPara("user_num","");
		String cpass = getPara("cpass","");
		String cname = getPara("cname","");
		String cdept = getPara("cdept","");
		String user_pos = getPara("user_pos","");
		String isort = getPara("isort", "1");
		String ctel = getPara("ctel","");
		String cphone = getPara("cphone","");
		String cemail = getPara("cemail","");
		String is_ld = getPara("is_ld", "0");
		String wx_userid = getPara("wx_userid","");
		String c_pro=getPara("c_pro","");
		
		String sql="select * from mis_user where ccode=?";
		Record record=Db.findFirst(sql,ccode);
		boolean isedit=true;
		if(record==null)
		{
			isedit=false;
			record=new Record();
			sql = "select count(1) from mis_user where user_num='" + user_num + "'";
			if (isedit) {
				sql += " and ccode <> '" + ccode + "'";
			}
			if (DBHelper.GetInt(sql) > 0) {
				renderJson(error("用户名已存在！"));
				return;
			}
			if (!isedit) {
				ccode = "0001";// 自动编号
				String maxcode = DBHelper.GetString("select max(ccode) from mis_user where ccode<>'admin'");
				if (!maxcode.equals("")) {
					ccode = String.valueOf(Long.parseLong(maxcode) + 1);
					ccode = SysUtil.getFillNum(ccode, 4);
				}
			}
			record.set("ccode", ccode);
			record.set("c_pro", c_pro);
		}

		if (cdept.equals("0")) {
			renderJson(error("请选择所属部门！"));
			return;
		}
		
		// 区分部门与班组
		String cwork_dept = cdept;
		String cdeptgroup = DBHelper.GetString("select cgroup from mis_org where ccode='" + cdept + "'");
		if (cdeptgroup.equals("3"))// 班组部门
		{
			cwork_dept = cdept.substring(0, cdept.length() - 2);// 上级工作部门
		}
		
		record.set("cname", cname);
		record.set("user_num", user_num);
		record.set("cdept", cdept);
		record.set("cwork_dept", cwork_dept);
		record.set("cpass", cpass);
		record.set("user_pos", user_pos);
		record.set("ctel", ctel);
		record.set("cemail", cemail);
		record.set("cphone", cphone);
		record.set("isort", isort);
		record.set("is_ld", is_ld);
		record.set("wx_userid", wx_userid);
		
		record.set("st_flag", "1");
		
		AjaxResult ajaxResult=null;
		if(DbUtils.save("mis_user", "ccode", record, isedit))
		{
			ajaxResult=success("保存成功！");
		}
		else
		{
			ajaxResult=error("保存失败！");
		}
		
		renderJson(ajaxResult);
	}
	
	public void delete()
	{
		String ccode=getPara("ccode","");
		String sql="delete from mis_user where ccode=?";
		if(Db.update(sql,ccode)>0)
		{
			renderJson(success("删除成功！"));
		}
		else
		{
			renderJson(error("删除失败！"));
		}
	}
	
	public void updateUser()
	{
		String ccode=getPara("ccode","");
		String col=getPara("col","");
		String cflag=getPara("cflag","");
		
		String sql = "update mis_user set "+col+"='" + cflag + "' where ccode='" + ccode + "'";
		if(Db.update(sql)>0)
		{
			renderJson(success("成功！"));
		}
		else
		{
			renderJson(error("失败！"));
		}
	}
	
	//选择用户
	public void selectuser()
	{
		String cpost=getPara("cpost","");
		set("cpost", cpost);
		
		String c_pro=getPara("c_pro","");
		set("c_pro", c_pro);
		
		render("system/sysuser_select.html");
	}
	
	public void export()
	{
		String fileName="用户.xlsx";
		
		String c_pro=getPara("c_pro","");
		String cpost = getPara("cpost", "");
		String cname = getPara("cname", "");
		String bm = getPara("cdept", "");
		boolean isleaf = getParaToBoolean("isleaf", true);

		String sqlSelect = "select t1.*,(case when is_ld='1' then 1 else 0 end) as isld "
				+ ",(select cname from mis_org where ccode=t1.cdept) as cbm ";
		String sqlExcept=" from mis_user t1 where 1=1 ";
		if (!bm.equals("")) {
			if (isleaf)// 下级部门用户
			{
				sqlExcept += " and t1.cdept like '" + bm + "%'";
			} else {
				sqlExcept += " and t1.cdept = '" + bm + "'";
			}
		}
		if (!cname.equals("")) {
			sqlExcept += " and (t1.cname like '%" + cname + "%' or t1.user_num like '%" + cname + "%')";
		}
		
		if(!cpost.equals(""))
		{
			sqlExcept+=" and t1.ccode not in (select ccode from mis_user_post where cpost='"+cpost+"')";
		}
		if(StrUtil.isNotEmpty(c_pro))
		{
			sqlExcept+=" and t1.c_pro='"+c_pro+"' ";
		}
		
		sqlExcept += " order by cdept,st_flag desc,isort,ccode";

		String sql=sqlSelect+sqlExcept;
		List<List<?>> rows = new ArrayList<List<?>>();
		List<Record> listRec=Db.find(sql);
		for (Record record : listRec) {
			List<?> row1 = CollUtil.newArrayList(record.getStr("ccode"),record.getStr("cname")
					,record.getStr("cdept"));
			rows.add(row1);
		}

		String path=FileUtils.getDownDir()+fileName;
		File file=new File(path); 
		if(file.exists())
		{
			file.delete();
		}
		BigExcelWriter writer= ExcelUtil.getBigWriter(path);
		//自定义标题别名
		writer.writeHeadRow(CollUtil.newArrayList("编号","姓名","部门"));

		// 一次性写出内容，使用默认样式
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		
		renderJson(success(fileName));
	}
	
}
